﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Identity;
using Volo.Abp.Settings;
using Volo.Abp.Uow;
using IdentityUser = Volo.Abp.Identity.IdentityUser;

namespace Volo.Abp.Account.Public.Web.Pages.Account
{
	public class VerifySecurityCodeModel : AccountPageModel
	{
		[BindProperty(SupportsGet = true)]
		[HiddenInput]
		public string ReturnUrl { get; set; }

		[HiddenInput]
		[BindProperty(SupportsGet = true)]
		public string ReturnUrlHash { get; set; }

		[BindProperty(SupportsGet = true)]
		[HiddenInput]
		public bool RememberMe { get; set; }

		[BindProperty(SupportsGet = true)]
		[HiddenInput]
		public string Provider { get; set; }

		[BindProperty]
		public string Code { get; set; }

		[BindProperty]
		public bool RememberBrowser { get; set; }

		public bool IsRememberBrowserEnabled { get; protected set; }

		[UnitOfWork]
		public virtual async Task OnGetAsync()
		{
			var identityUser = await base.SignInManager.GetTwoFactorAuthenticationUserAsync();
			if (identityUser == null)
			{
				throw new UserFriendlyException(base.L["VerifySecurityCodeNotLoggedInErrorMessage"]);
			}
			this.CheckCurrentTenant(identityUser.TenantId);
			var flag = await this.IsRememberBrowserEnabledAsync();
			this.IsRememberBrowserEnabled = flag;
		}

		[UnitOfWork]
		public virtual async Task<IActionResult> OnPostAsync()
		{
			SignInManager<IdentityUser> signInManager = SignInManager;
			string provider = this.Provider;
			string code = this.Code;
			bool rememberMe = this.RememberMe;
			var flag = await this.IsRememberBrowserEnabledAsync();
			var signInResult = await signInManager.TwoFactorSignInAsync(provider, code, rememberMe, flag && this.RememberBrowser);
			signInManager = null;
			provider = null;
			code = null;
			IActionResult result;
			if (signInResult.Succeeded)
			{
				result = base.RedirectSafely(this.ReturnUrl, this.ReturnUrlHash);
			}
			else
			{
				if (signInResult.IsLockedOut)
				{
					base.Alerts.Warning(base.L["UserLockedOutMessage"]);
				}
				base.Alerts.Warning(base.L["InvalidSecurityCode"]);
				result = this.Page();
			}
			return result;
		}

		protected virtual async Task<bool> IsRememberBrowserEnabledAsync()
		{
			return await base.SettingProvider.IsTrueAsync("Abp.Account.TwoFactorLogin.IsRememberBrowserEnabled");
		}
	}
}
